import 'dart:convert';
import 'package:http/http.dart' as http;

class WeatherService {
  // 使用模拟数据，避免API密钥问题
  Future<WeatherInfo> getWeather(double lat, double lon) async {
    try {
      // 尝试调用API（如果有API密钥）
      // 实际项目中，替换下面的API密钥
      const String apiKey = 'e7e6ea12c3014ce1aebe4071674baa33';

      if (apiKey != 'YOUR_HEFENG_API_KEY') {
        // 如果有真实API密钥，则调用真实API
        final response = await http.get(
          Uri.parse('https://devapi.qweather.com/v7/weather/now?location=$lon,$lat&key=$apiKey'),
        );

        if (response.statusCode == 200) {
          final data = jsonDecode(response.body);

          // 获取城市信息
          final cityResponse = await http.get(
            Uri.parse('https://devapi.qweather.com/v7/geo/location?location=$lon,$lat&key=$apiKey'),
          );

          String cityName = '未知城市';
          if (cityResponse.statusCode == 200) {
            final cityData = jsonDecode(cityResponse.body);
            if (cityData['code'] == '200' && cityData['location'] != null && cityData['location'].isNotEmpty) {
              cityName = cityData['location'][0]['name'];
            }
          }

          if (data['code'] == '200') {
            final now = data['now'];
            return WeatherInfo(
              temperature: double.parse(now['temp']),
              condition: now['text'],
              icon: now['icon'],
              city: cityName,
              clothingSuggestion: getClothingSuggestion(double.parse(now['temp'])),
            );
          }
        }
      }

      // 如果API调用失败或没有API密钥，返回模拟数据
      return _getMockWeather();
    } catch (e) {
      print('获取天气信息失败: $e');
      // 如果发生异常，返回模拟天气信息
      return _getMockWeather();
    }
  }

  // 获取模拟天气信息（当API调用失败时使用）
  WeatherInfo _getMockWeather() {
    // 获取当前时间来决定天气状况
    final now = DateTime.now();
    final hour = now.hour;

    // 根据时间生成不同的天气状况
    String condition;
    String icon;
    double temperature;

    if (hour >= 6 && hour < 12) {
      condition = '晴';
      icon = '100';
      temperature = 22 + (now.minute % 10);
    } else if (hour >= 12 && hour < 18) {
      condition = '多云';
      icon = '101';
      temperature = 25 + (now.minute % 8);
    } else {
      condition = '阴';
      icon = '104';
      temperature = 18 + (now.minute % 6);
    }

    return WeatherInfo(
      temperature: temperature,
      condition: condition,
      icon: icon,
      city: '当前城市',
      clothingSuggestion: getClothingSuggestion(temperature),
    );
  }

  // 根据温度给出穿衣建议
  static String getClothingSuggestion(double temperature) {
    if (temperature > 30) {
      return '天气炎热，建议穿轻薄、透气的衣物，如短袖T恤、短裤等，出门记得防晒。';
    } else if (temperature > 25) {
      return '天气温暖，建议穿轻便的衣物，如短袖、薄长裤等。';
    } else if (temperature > 20) {
      return '天气舒适，建议穿薄长袖或短袖搭配外套，裤装为宜。';
    } else if (temperature > 15) {
      return '天气微凉，建议穿长袖衬衫、薄毛衣或薄外套等。';
    } else if (temperature > 10) {
      return '天气较凉，建议穿毛衣、夹克等保暖衣物。';
    } else if (temperature > 5) {
      return '天气寒冷，建议穿厚外套、毛衣、围巾等保暖衣物。';
    } else {
      return '天气严寒，建议穿羽绒服、厚毛衣、保暖内衣等多层次穿着，注意保暖。';
    }
  }
}

class WeatherInfo {
  final double temperature;
  final String condition;
  final String icon;
  final String city;
  final String clothingSuggestion;

  WeatherInfo({
    required this.temperature,
    required this.condition,
    required this.icon,
    required this.city,
    required this.clothingSuggestion,
  });

  // 获取和风天气图标URL
  String get iconUrl => 'https://a.hecdn.net/img/common/icon/202106d/$icon.png';
}

